package com.datastructure.test.maxlengthofbucketserial;

import com.datastructure.test.maxlengthofrepeatingserial.MaxLengthOfRepeatingSerial;

import java.util.Iterator;
import java.util.Stack;

public class MaxLengthOfBucketSerial {

    public static void main(String[] args) {
        String data = "(())";
        MaxLengthOfBucketSerial maxLengthOfBucketSerial=new MaxLengthOfBucketSerial();
        int i = maxLengthOfBucketSerial.longestValidParentheses(data);
        System.out.println(i);
    }

    public int longestValidParentheses (String s) {
        // write code here
        if(s==null||s.equals(")(")||s.length()==1){
            return 0;
        }
        int sum = 0;
        byte[] bytes = s.getBytes();
        Stack<Byte> first = new Stack<>();
        Stack<Byte> second = new Stack<>();
        for (byte aByte : bytes) {
            first.add(aByte);
        }
        Iterator<Byte> iterator = first.iterator();
        while (iterator.hasNext()){
            if(second.isEmpty()){
                second.add(iterator.next());
            } else {
                Byte next = iterator.next();
                Byte pop = second.pop();
                if(next+pop==81){
                    sum+=2;
                } else {
                    second.add(pop);
                    second.add(next);
                }
            }
        }
        return sum;
    }
}
